//
//  NoAttentionViewController.m
//  SouthChina
//
//  Created by Mr.Y on 14/11/5.
//  Copyright (c) 2014年 科创. All rights reserved.
//

#import "PublicListController.h"
#import "PublicAccountCell.h"
#import "PublicAccount.h"
#import "PublicInforDetailViewController.h"
#import "PublicAccountTypeViewCell.h"
#import "XLCycleScrollView.h"
#import "DataDict.h"
@interface PublicListController ()<UISearchBarDelegate, UITableViewDataSource,UITableViewDelegate,XLCycleScrollViewDatasource,XLCycleScrollViewDelegate,PublicAccountCellDelegate>

{
    UISearchDisplayController *searchDisplayController;
    XLCycleScrollView * veBillboard;
    NSString *sSearchKey;
    UITextField *searchField;
}
@property (strong, nonatomic) UISearchBar * searchBar;

@end

@implementation PublicListController


@synthesize kindType,appList,appType;


- (void)viewDidLoad {
    [super viewDidLoad];
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardWillShowNotification object:nil];
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(keyboardWillHide:) name:UIKeyboardWillHideNotification object:nil];
    
    sSearchKey = @"";
    
     CGFloat Hight;
     Hight = self.view.frame.size.height-TITLE_BAR_HEGIHT-TABBARHEIGHT-35;
    
    _appListTable = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, Hight) style:UITableViewStyleGrouped];
    _appListTable.delegate =self;
    _appListTable.dataSource = self;
    [_appListTable setBackgroundColor:[UIColor whiteColor]];
    
    [self.view addSubview:_appListTable];
    
    if ([kindType isEqualToString:@"3"] )
    {
        [self addTitleBarWithBackBtn:@"应用搜索" needReturn:YES];
        //搜索框占44高，需要把列表框下移
        _searchBar = [[UISearchBar alloc] initWithFrame:CGRectMake(0, TITLE_BAR_HEGIHT+YNEW, SCREEN_WIDTH, 44)];
        _searchBar.showsCancelButton=NO;
        _searchBar.barStyle=UIBarStyleDefault;
        _searchBar.keyboardType = UIKeyboardTypeDefault;
        _searchBar.placeholder = @"应用名称";
        _searchBar.delegate = self;
        //ios7.0 之后UISearchBar 结构发生了变化
        if ([[[UIDevice currentDevice] systemVersion] floatValue]<7.0)
            searchField=[_searchBar.subviews objectAtIndex:1];
        else
            searchField=[((UIView *)[_searchBar.subviews objectAtIndex:0]).subviews lastObject];
        [searchField setReturnKeyType:UIReturnKeyDone];
        
        [self.view addSubview:_searchBar];
       // _appListTable.tableHeaderView = _searchBar;
        Hight = self.view.frame.size.height-TITLE_BAR_HEGIHT-YNEW-44;
        _appListTable.frame = CGRectMake(0, TITLE_BAR_HEGIHT+YNEW+44, SCREEN_WIDTH, Hight);
    }
    else if ([kindType isEqualToString:@"0"])
    {
        //添加橱窗列表
        veBillboard  = [[XLCycleScrollView alloc] initWithFrame:CGRectMake(0,0,SCREEN_WIDTH, 150)];
        veBillboard.delegate = self;
        veBillboard.datasource = self;
        veBillboard.initervaltime = 99999;
        _appListTable.tableHeaderView = veBillboard;
    }
    else if ([kindType isEqualToString:@"4"])
    {
        [self addTitleBarWithBackBtn:self.title needReturn:YES];
        Hight = self.view.frame.size.height-TITLE_BAR_HEGIHT;
        _appListTable.frame = CGRectMake(0, TITLE_BAR_HEGIHT, SCREEN_WIDTH, Hight);
    }

    
    // Do any additional setup after loading the view.
}

-(void)viewDidUnload
{
    [super viewDidUnload];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillShowNotification
                                                  object:nil];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillHideNotification
                                                  object:nil];
}

# pragma mark Keyboard Notifications

- (void)keyboardWillShow:(NSNotification *)notification {
    if ([kindType isEqualToString:@"3"] ){
        NSDictionary *userInfo = [notification userInfo];
        NSValue *aValue = [userInfo objectForKey:UIKeyboardFrameEndUserInfoKey];
        CGRect keyboardRect = [aValue CGRectValue];
        int height = keyboardRect.size.height;
        CGFloat Hight;
        Hight = self.view.frame.size.height-TITLE_BAR_HEGIHT-YNEW-44-height;
        _appListTable.frame = CGRectMake(0, TITLE_BAR_HEGIHT+YNEW+44, SCREEN_WIDTH, Hight);
    }
   
}

- (void)keyboardWillHide:(NSNotification *)notification {
    if ([kindType isEqualToString:@"3"] )
    {
        CGFloat Hight;
        Hight = self.view.frame.size.height-TITLE_BAR_HEGIHT-YNEW-44;
        _appListTable.frame = CGRectMake(0, TITLE_BAR_HEGIHT+YNEW+44, SCREEN_WIDTH, Hight);
    }
   
}

//完成按钮后的操作
-(void)searchBarSearchButtonClicked:(UISearchBar *)searchBar
{
    [searchField resignFirstResponder];
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

-(void)refreshSearchBar:(NSString *)SearchKey{
    
    NSArray * Searchapp = [PublicAccountDao searcherNodePublicAccount:SearchKey];
    //查询结果是否有已经关注应用
    NSPredicate *predicate1 = [NSPredicate predicateWithFormat:@"subscribeStatus== %@", @"1"];
    NSArray *MyAPP = [Searchapp filteredArrayUsingPredicate:predicate1];
    NSPredicate *predicate2 = [NSPredicate predicateWithFormat:@"subscribeStatus== %@", @"0"];
    NSArray *NoMyAPP = [Searchapp filteredArrayUsingPredicate:predicate2];
    
    NSMutableArray * apptype =[[NSMutableArray alloc]init];
    
    if([MyAPP count] !=0)
    {
        DataDict *dict =   [[DataDict alloc]init];
        dict.dictdataValue =@"我的应用";
        dict.dictdataName =@"1";
        dict.otheArray = MyAPP;
        [apptype addObject:dict];
    }
    
    if([NoMyAPP count] != 0)
    {
        DataDict *dict =   [[DataDict alloc]init];
        dict.dictdataValue =@"未关注应用";
        dict.dictdataName =@"0";
        dict.otheArray = NoMyAPP;
        [apptype addObject:dict];
    }
    
    appType = apptype;
}

-(BOOL)textFieldShouldReturn:(UITextField *)textField
{
    [textField resignFirstResponder];
    return YES;
}

// called when text changes (including clear)
- (void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText
{
    
    NSLog(@"%@--",searchText);
    sSearchKey = searchText;
    [self refreshSearchBar:sSearchKey];
    [_appListTable reloadData];
}

// called when cancel button pressed
- (void)searchBarCancelButtonClicked:(UISearchBar *)searchBar{
    [self searchBar:searchBar textDidChange:@""];
}

//精品分类中的橱窗数量
- (NSInteger)numberOfPages
{
    return _appAD.count;
}

//橱窗图片设置
- (UIView *)pageAtIndex:(NSInteger)index
{
    UIImageView * l = [[UIImageView alloc]initWithFrame:veBillboard.bounds];

    PublicAccount * publicaccount = [_appAD objectAtIndex:index];
    NSURL *url = [NSURL URLWithString: [publicaccount getValue:@"bannerPic"]];
    [l setImageWithURL:url placeholderImage:[UIImage imageNamed:@"empty_photo"]];
    return l;
}

//橱窗图片点击
- (void)didClickPage:(XLCycleScrollView *)csView atIndex:(NSInteger)index
{
    PublicAccount * publicaccount = [_appAD objectAtIndex:index];
    
    if([publicaccount isSubscribeStatus])
    {
        //关注应用，直接打开
        MessageViewController * message = [[MessageViewController alloc] init];
        NSDictionary *dicc = @{@"sessionType":MESSAGE_TYPE_P2P,@"messtype":@"3",@"record_DB_ID":publicaccount.appId,
                               @"recordID":publicaccount.appId};
        message.sessInfo = dicc;
        
        [kAppDelegate.iCSDrawerController.navigationController pushViewController:message animated:YES];
    }
    else
    {
        PublicInforDetailViewController * detail = [[PublicInforDetailViewController alloc] init];
        detail.publicaccount = publicaccount;
        [kAppDelegate.iCSDrawerController.navigationController pushViewController:detail animated:NO];
    }
}


- (void)publicAccountCell:(PublicAccountCell *)cell didTapButton:(UIButton *)sender
{
    NSLog(@"=======测试点击添加应用按钮");

    PublicAccount * publicaccount = cell.publicAccount;
    
    if([kindType isEqualToString:@"2"] )
    {
        //添加删除首页
        //20150828改造，添加应用时给一个大于1000的序号，并且放在首页应用最后面。取消应用时序号为0
        //在使用的app有多少个
        // NSPredicate *predicateUsers = [NSPredicate predicateWithFormat:@"mTYPE != %@",@"O"];
        //NSArray *usersList = [allList filteredArrayUsingPredicate:predicateUsers];
        //我的应用中包括加入首页和未加入首页的，为了排序，要过滤掉未加入首页的应用 isHome=0
        NSUInteger nAppTotalCnt = [[[appType objectAtIndex:0] otheArray]count];
        NSString *sort = @"0";//默认是取消首页
        if ([@"0" isEqualToString:publicaccount.isHome]) {
           NSPredicate *predicateapps = [NSPredicate predicateWithFormat:@"isHome == %@",@"1"];
           NSArray *AppHomeList = [[[appType objectAtIndex:0] otheArray] filteredArrayUsingPredicate:predicateapps];
           int userSort = 1000+AppHomeList.count+1;
           sort = [NSString stringWithFormat:@"%d",userSort];
        }
        publicaccount.userSort = sort;
        NSDictionary *params = @{@"appId":publicaccount.appId,@"sort":sort,@"isHome":[publicaccount isHomeApp]?@"0":@"1"};
        
        [MBProgressHUD showHUDAddedTo:self.view animated:YES];
        [DE serverCall:@"updateSingleAppHomeStatus" params:params callback:^(BOOL success, int code, NSString *desc, NSDictionary *data,NSDictionary*param) {
            [MBProgressHUD hideHUDForView:self.view animated:YES];
            NSLog(@"%@",data);
            if(success)
            {
                [publicaccount putValue:sort key:@"userSort"];
                [publicaccount setIsHomeApp:![publicaccount isHomeApp]];
                [PublicAccountDao updatePublicAccount:publicaccount];
                //发送通知
                [[NSNotificationCenter defaultCenter] postNotificationName:PUBLIC_ATTENTION_BROADCAST object:nil];
               [self showAlerHUD:[publicaccount isHomeApp]?@"加入首页成功！":@"取消首页展示成功！" framewidth:120];
                [sender setTitle:[publicaccount isHomeApp]?@"取消首页展示":@"加入首页" forState:UIControlStateNormal];
            }
            else{
               [self showAlerHUD:[publicaccount isHomeApp]?@"取消首页展示失败！":@"加入首页失败！" framewidth:120];
            }
        }];
        
    }
    else if([publicaccount isSubscribeStatus])
    {
        //关注应用，直接打开
        PublicAccount *publicAccount  = publicaccount;
        MessageViewController * message = [[MessageViewController alloc] init];
        NSDictionary *dicc = @{@"sessionType":MESSAGE_TYPE_P2P,@"messtype":@"3",@"record_DB_ID":publicAccount.appId,
                               @"recordID":publicAccount.appId};
        message.sessInfo = dicc;
        [kAppDelegate.iCSDrawerController.navigationController pushViewController:message animated:NO];
    }
    else
    {
        NSString *sessonid = [NSString stringWithFormat:@"%@_%@",MESSAGE_TYPE_P2P,publicaccount.appId];
        
        NSDictionary *params = @{@"publicId":publicaccount.appId,@"userId":DE.userId};
        [MBProgressHUD showHUDAddedTo:self.view animated:YES];
        
        [DE serverCall:[publicaccount isSubscribeStatus]?@"unsubscribe":@"subscribe" params:params callback:^(BOOL success, int code, NSString *desc, NSDictionary *data,NSDictionary*param) {
            [MBProgressHUD hideHUDForView:self.view animated:YES];
            NSLog(@"%@",data);
            if(success && [data objectForKey:@"result"])
            {
                if ([publicaccount isSubscribeStatus]) {
                    //删除该条会话
                    [MessageSessionDao deleteMessageSession:sessonid];
                    //20150820 清除message
                    [MessageDao deleteMessageBysessionId:sessonid];
                }else{
                    [publicaccount setPublicIsReceive:YES];
                }
                //20150929如果是取消关注，则同时要置ishome为0
                if([publicaccount isSubscribeStatus])
                    [publicaccount setIsHomeApp:NO];
                [publicaccount setPublicSubscribeStatus:![publicaccount isSubscribeStatus]];
                [PublicAccountDao updatePublicAccount:publicaccount];
                //发送通知
                [[NSNotificationCenter defaultCenter] postNotificationName:PUBLIC_ATTENTION_BROADCAST object:nil];
                UIAlertView *aler =  [[UIAlertView alloc] initWithTitle:@"提示" message:[publicaccount isSubscribeStatus]?@"添加成功！":@"取消关注成功！" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
                [aler show];
                [sender setTitle:@"已关注" forState:UIControlStateNormal];
                //搜索的需要重新读取数据
                if([kindType isEqualToString:@"3"])
                {
                    [self refreshSearchBar:sSearchKey];
                }
                [_appListTable reloadData];
            }
            else{
                UIAlertView *aler =  [[UIAlertView alloc] initWithTitle:@"提示" message:[publicaccount isSubscribeStatus]?@"取消关注失败！":@"添加失败！" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
               [aler show];
            }
        }];
    }
}

//重写提示效果(个性化)
-(void)showAlerHUD:(NSString*)text framewidth:(CGFloat) hudwidth
{
    BDKNotifyHUD * hudex = [[BDKNotifyHUD alloc] initWithImageEX:[UIImage imageNamed:@""]  text:text hudWidth:hudwidth];
    hudex.center = CGPointMake(self.view.center.x,SCREEN_HEIGHT-130);
    [self.view addSubview:hudex];
    [hudex presentWithDuration:0.6 speed:0.3f inView:self.view completion:^{
        [hudex removeFromSuperview];
    }];
}

//列表组
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    //分类应用只显示分类数据列表，就只设置一个列表组
    if([kindType isEqualToString:@"1"])
        return 1;
    
    return appType.count;
}

//根据分组返回每组的数量
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    //分类应用只显示分类数据列表，此处返回分类数量
    if([kindType isEqualToString:@"1"])
        return appType.count;
    
    
    return [[[appType objectAtIndex:section] otheArray]count];
}

- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section{
    //分类应用，我的应用不用显示列表组的头信息
    if([kindType isEqualToString:@"1"] || [kindType isEqualToString:@"2"] || [kindType isEqualToString:@"4"])
        return nil;
    
    return [[appType objectAtIndex:section] dictdataValue];
}

//指定标题的高度
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    
    if([kindType isEqualToString:@"1"] || [kindType isEqualToString:@"2"] || [kindType isEqualToString:@"4"])
        return 0.1;
    
    return 30;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if ([kindType isEqualToString:@"1"]) {
        static NSString * CellIdentifier = @"PublicAccountTypeViewCell";
        PublicAccountTypeViewCell * cell = [[[NSBundle mainBundle] loadNibNamed:CellIdentifier owner:self options:nil] objectAtIndex:0];
        cell.labTitle.text =[[appType objectAtIndex:indexPath.row] dictdataValue];
        NSArray *pubaccountarr = [[appType objectAtIndex:indexPath.row] otheArray];
        [cell SetCellHeadImage:pubaccountarr];
        
        cell.labNum.text = [NSString stringWithFormat:@"%lu",(unsigned long)[[[appType objectAtIndex:indexPath.row] otheArray] count]];
        return cell;
    }
    
    static NSString * CellIdentifier = @"PublicAccountCell";
    PublicAccountCell * cell = [[[NSBundle mainBundle] loadNibNamed:CellIdentifier owner:self options:nil] objectAtIndex:0];
    
    PublicAccount * publicaccount = [[[appType objectAtIndex:indexPath.section]otheArray] objectAtIndex:indexPath.row];
    //设置列表展示，包括调试、官方的标签,提醒数
    [cell setPublicAccountCell:publicaccount];
    cell.delegate = self;
    cell.addOpneMyApp.layer.masksToBounds = YES;
    cell.addOpneMyApp.layer.cornerRadius = 6;
    
    if([publicaccount isSubscribeStatus])
    {
        //已经关注
        if( [kindType isEqualToString:@"2"] )
        {
            cell.badgerNumer.hidden = YES;
            if([publicaccount isHomeApp])
            {
                [cell.addOpneMyApp setTitle:@"取消首页" forState:UIControlStateNormal];
                [cell.addOpneMyApp setBackgroundColor:[UIColor redColor]];
            }
            else
            {
                [cell.addOpneMyApp setTitle:@"加入首页" forState:UIControlStateNormal];
                [cell.addOpneMyApp setBackgroundColor:[UIColor colorWithRed:0.0f/255.0f green:131.0f/255.0f blue:255.0f/255.0f alpha:1.0f]];
            }
        } ///4
        else
        {
            NSLog(@"DSAFDASFAS");
            cell.badgerNumer.hidden = YES;
            [cell.addOpneMyApp setTitle:@"已关注" forState:UIControlStateNormal];
           [cell.addOpneMyApp setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
            cell.addOpneMyApp.backgroundColor = [UIColor whiteColor];
        }
    }
    else
    {
        //未关注
        //[cell.addOpneMyApp setTitle:@"立即关注" forState:UIControlStateNormal];
        [cell.addOpneMyApp setTitle:@"关注" forState:UIControlStateNormal];
        [cell.addOpneMyApp setBackgroundColor:[UIColor colorWithRed:0.0f/255.0f green:131.0f/255.0f blue:255.0f/255.0f alpha:1.0f]];
    }
    
    return cell;
}
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    if ([kindType isEqualToString:@"1"])
    {
        //跳转分类明细页面
        //点击搜索，单独跳转一个搜索页面
        NSLog(@"ASFDASFASDFASDFASDF");
        PublicListController *search = [[PublicListController alloc] init];
        search.kindType=@"4";
        search.deleget = self;
        search.title = [[appType objectAtIndex:indexPath.row] dictdataValue];
        NSArray * oneType = [[NSArray alloc] initWithObjects:[appType objectAtIndex:indexPath.row], nil];
        search.appType = oneType;
        
        [kAppDelegate.iCSDrawerController.navigationController pushViewController:search animated:NO];
        return;
    }

    PublicAccount * publicaccount = [[[appType objectAtIndex:indexPath.section]otheArray] objectAtIndex:indexPath.row];
    
    if([publicaccount isSubscribeStatus])
    {
        //关注应用，直接打开
        NSLog(@"############### 直接打开");
        MessageViewController * message = [[MessageViewController alloc] init];
        NSDictionary *dicc = @{@"sessionType":MESSAGE_TYPE_P2P,@"messtype":@"3",@"record_DB_ID":publicaccount.appId,
                               @"recordID":publicaccount.appId};
        message.sessInfo = dicc;
        
       // [kAppDelegate.iCSDrawerController.navigationController pushViewController:message animated:YES];动画效果YES时，新的页面背景后有上一个页面的残影
        [kAppDelegate.iCSDrawerController.navigationController pushViewController:message animated:NO];
    }
    else
    {
        PublicInforDetailViewController * detail = [[PublicInforDetailViewController alloc] init];
        detail.publicaccount = publicaccount;
        [kAppDelegate.iCSDrawerController.navigationController pushViewController:detail animated:NO];
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return TABLECELLHIGHT;
}


@end
